<template>
    <el-dialog :title="titleMap[mode]" v-model="visible" :width="1800" destroy-on-close @closed="close" :close-on-click-modal="false" :close-on-press-escape="mode != 'show' ? false : true" align-center>
        <el-form :model="form" :rules="rules" :disabled="mode=='show'" label-width="100" ref="dialogForm">
            <el-row :gutter="1">
                <el-col :span="6">
                    <el-form-item label="目标仓库" prop="ware_id">
						<el-select v-model="form.ware_id" placeholder="请选择" filterable clearable @change="wareChange">
							<el-option v-for="item in wareList" :key="item.id" :label="item.ware_name" :value="item.id"></el-option>
						</el-select>
					</el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="日期" prop="send_date">
						<el-date-picker v-model="form.send_date" type="date" placeholder="请选择日期" :value-format="'YYYY-MM-DD'" style="width:100%"  @change="updateFields"/>
					</el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="车牌号" prop="car_code">
                        <el-input v-model="form.car_code" placeholder="请输入车牌号" clearable @blur="updateFields"></el-input>
					</el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="1">
                <el-col :span="6">
                    <el-form-item label="司机电话" prop="car_mobile">
                        <el-input v-model="form.car_mobile" placeholder="请输入司机电话" clearable @blur="updateFields"></el-input>
					</el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="备注" prop="remark">
						<el-input v-model="form.remark" placeholder="备注" clearable @blur="updateFields"></el-input>
					</el-form-item>
                </el-col>
            </el-row>

            <div class="top_flex">
                <div style="width: 60%;">
                    <span>新增</span>
                    <div style="display: flex;align-items: center;">
                        <el-input v-model="bar_code" ref="barCodeInput" placeholder="放入条码" style="width: 200px" @keyup.enter="getTable()" :readonly="!form.ware_id"></el-input>
                        <el-tooltip content="录入条码需要先行选择目标仓库" placement="top" width="200">
							<el-icon style="margin-left: 10px;" size="16"><el-icon-InfoFilled /></el-icon>
						</el-tooltip>
                        <span style="margin-left: 10px;">总匹数: {{total_count}}</span>
                        <span style="margin-left: 10px;">总码数: {{form.total_num}}</span>
                        <span style="margin-left: 10px;">总加工费: {{form.total_price}}</span>
                        <span style="margin-left: 10px;">总重量: {{net_weight_total}}</span>
                    </div>
                </div>
                <div>
                    <span>删除</span>
                    <el-input v-model="remove_bar_code" ref="removeBarCodeInput" placeholder="放入条码" @keyup.enter="removeCode"></el-input>
                </div>
            </div>
            <div style="height: 600px;">
                <el-auto-resizer>
                    <template #default="{ width, height }">
                        <el-table-v2 border :columns="columns" :data="form.detail" :width="width" :height="height" row-key="index" @select-change="handleSelectChange" :row-height="40" />
                    </template>
                </el-auto-resizer>
            </div>
        </el-form>
    </el-dialog>
</template>

<script>

import config from '@/config'
export default {
    emits: ['success', 'closed'],
    data() {
        return {
            mode: "add",
            titleMap: {
                add: '新增供应商发货',
                copy: '新增供应商发货',
                edit: '编辑供应商发货',
                show: '查看供应商发货',
            },
            visible: false,
            isSaveing: false,
            form: {
                id: "",
                ware_id: "",
                car_code: "",
                car_mobile: "",
                send_date: this.moment().format('YYYY-MM-DD'),
                remark: "",
                detail: [],
                total_num: "",
                total_price: "",
            },
            rules: {
                ware_id: [ {required: true, message: '请选择仓库'} ],
                send_date: [ {required: true, message: '请选择发货日期'} ],
            },
            wareList: [],
            bar_code: "",
            test_code: "",
            remove_bar_code: "",
            total_count: "",
            net_weight_total: "",
            table_index: 0,
            columns: [
                {
                    title: '序号',
                    dataKey: 'index',
                    width: 80,
                    align: 'center'
                },
                {
                    title: '条码',
                    dataKey: 'roll_code',
                    width: 180,
                    align: 'center'
                },
                {
                    title: '品名',
                    dataKey: 'goods_name',
                    width: 180,
                    align: 'center',
                },
                {
                    title: '货号',
                    dataKey: 'goods_code',
                    width: 150,
                    align: 'center',
                },
                {
                    title: '花型',
                    dataKey: 'flower',
                    width: 180,
                    align: 'center',
                },
                {
                    title: '颜色',
                    dataKey: 'color',
                    width: 150,
                    align: 'center'
                },
                {
                    title: 'Color',
                    dataKey: 'colorName',
                    width: 150,
                    align: 'center',
                    cellRenderer: ({ rowData }) => {
                        return rowData.colorName ? rowData.colorName : ''
                    }
                },
                {
                    title: '码数',
                    dataKey: 'code_number',
                    width: 100,
                    align: 'center'
                },
                {
                    title: '折码',
                    dataKey: 'folding',
                    width: 100,
                    align: 'center',
                    cellRenderer: ({ rowData }) => {
                        return rowData.folding ? rowData.folding : ''
                    }
                },
                {
                    title: '净重',
                    dataKey: 'net_weight',
                    width: 100,
                    align: 'center'
                },
                ...(this.$TOOL.data.get("COLUMNSAUTH").includes('applysend.gram_weight') ? [{
                    title: '克重',
                    dataKey: 'gram_weight',
                    width: 100,
                    align: 'center'
                }] : []),
                ...(this.$TOOL.data.get("COLUMNSAUTH").includes('applysend.base_price') ? [{ 
                    title: '成本价',
                    dataKey: 'base_price',
                    width: 100,
                    align: 'center'
                }] : []),
                ...(this.$TOOL.data.get("COLUMNSAUTH").includes('applysend.process_price') ? [{
                    title: '加工费',
                    dataKey: 'process_price',
                    width: 120,
                    align: 'center'
                }] : []),
                ...(this.$TOOL.data.get("COLUMNSAUTH").includes('applysend.volume') ? [{
                    title: '体积',
                    dataKey: 'volume',
                    width: 120,
                    align: 'center'
                }] : []),
                ...(this.$TOOL.data.get("COLUMNSAUTH").includes('applysend.apply_name') ? [{
                    title: '供应商',
                    dataKey: 'apply_name',
                    width: 100,
                    align: 'center'
                }] : []),
                ...(this.$TOOL.data.get("COLUMNSAUTH").includes('applysend.dye_apply_name') ? [{
                    title: '染厂',
                    dataKey: 'dye_apply_name',
                    width: 100,
                    align: 'center'
                }] : []),
                ...(this.$TOOL.data.get("COLUMNSAUTH").includes('applysend.process_apply_name') ? [{
                    title: '加工厂',
                    dataKey: 'process_apply_name',
                    width: 100,
                    align: 'center'
                }] : []),
            ],
            inputRefs: new Map()
        }
    },
    created() {
        this.timeInput = this.common.debounce(this.timeInput, 5000);
        // this.removeCode = this.common.debounce(this.removeCode, 500);
	},
    mounted() {
		this.getWare();
    },
    methods: {
        //显示
        open(mode = 'add') {
            this.mode = mode;
            this.visible = true;
            return this
        },
        close() {
            this.$emit('closed')
            this.submit()
        },
        //表单提交方法
        async submit() {
            if(!this.form.ware_id) return
            if(this.mode == 'show') return
            // var res = []
            if (this.form.id) {
                // res = await this.$API.ware.ware.applysend.edit.post(this.form);
                this.$emit('success', this.form, this.mode)
            } else {
                var res = await this.$API.ware.ware.applysend.add.post(this.form);
                if (res.code == 1) {
                    this.$emit('success', this.form, this.mode)
                    this.form.id = this.form.id?this.form.id:res.data.id
                    // if(this.form.id){
                    //     this.setData({id: this.form.id})
                    // }
                }else {
                    this.$alert(res.message, "提示", {type: 'error'})
                    this.remove_bar_code = this.bar_code
                    this.removeCode()
                }
            }
        },
        //表单注入数据
        async setData(data) {
            this.form.id = data.id
            var res = await this.$API.ware.ware.applysend.detail.get({id: data.id});
            this.form.ware_id = res.data.ware_id
            this.form.car_code = res.data.car_code
            this.form.car_mobile = res.data.car_mobile
            this.form.send_date = res.data.send_date
            this.form.remark = res.data.remark
            this.total_count = res.data.total_count
            this.form.total_num = res.data.total_num
            this.form.total_price = res.data.total_money
            this.net_weight_total = res.data.net_weight_total
            this.table_index = res.data.detail.length
            let array = []
            res.data.detail.map(item=>{
                array.push({
                    id: item.id,
                    index: item.index,
                    inspect_id: item.inspect_id,
                    roll_code: item.inspect?.roll_code,
                    goods_code: item.inspect?.goods_code,
                    goods_name: item.inspect?.goods_name,
                    net_weight: item.inspect?.net_weight,
                    number: item.inspect?.number,
                    code_number: item.inspect?.code_number,
                    folding: item.inspect?.folding,
                    gram_weight: item.inspect?.gram_weight,
                    color: item.inspect?.color,
                    colorName: item.inspect?.color_en,
                    flower: item.inspect?.flower,
                    base_price: item.inspect?.base_price,
                    apply_name: item.inspect?.ware?.apply?.apply_name,
                    process_price: item.process_price,
                    remark: item.remark,
                    volume: item.volume,
                    total_price: (Number(item.price) * Number(item.inspect?.code_number)).toFixed(2),
                })
            })
            this.form.detail = array
        },
        // 仓库列表
		async getWare() {
			var res = await this.$API.basic.ware.all.get();
			this.wareList = res.data
		},
        async getTable(){
            if(!this.bar_code) return
            var res = await this.$API.ware.ware.applysend.scan.get({roll_code: this.bar_code,action_type: 1,send_id: this.form.id})
            if(res.code == 1){
                // 创建新的Audio实例播放成功声音，避免连续播放时相互干扰
                const successAudio = new Audio(`${config.API_URL}//audio/ok.wav`);
                successAudio.play();
                this.form.total_num = (Number(res.data.code_number) + Number(this.form.total_num)).toFixed(2)
                this.net_weight_total = (Number(res.data.net_weight) + Number(this.net_weight_total)).toFixed(2)
                this.form.total_price = (Number(res.data.purchaseware?.price) * Number(this.form.total_price)).toFixed(2)
                const maxIndex = this.form.detail.length > 0 ? Math.max(...this.form.detail.map(item => item.index)) : 0
                const newIndex = maxIndex + 1
                this.table_index = newIndex
                let array = []
                let form = {
                    index: newIndex,
                    inspect_id: res.data.id,
                    roll_code: res.data.roll_code,
                    goods_code: res.data.goods_code,
                    goods_name: res.data.goods_name,
                    net_weight: res.data.net_weight,
                    code_number: res.data.code_number,
                    number: res.data.number,
                    folding: res.data.folding,
                    gram_weight: res.data.gram_weight,
                    color: res.data.color,
                    colorName: res.data.color_en,
                    flower: res.data.flower,
                    base_price: res.data.base_price,
                    apply_name: res.data.ware?.apply?.apply_name,
                    process_price: res.data.purchaseware?.price,
                    volume: res.data.goodsName?.volume,
                }
                this.bar_code = ""
                setTimeout(()=>{
                    array.push(form)
                    this.form.detail = [...array, ...this.form.detail]
                },10)
                this.total_count += 1
            }else{
                // 创建新的Audio实例播放错误声音，避免连续播放时相互干扰
                const errorAudio = new Audio(`${config.API_URL}/audio/error.wav`);
                errorAudio.play();
                this.$message.error(res.message)
                this.$refs.barCodeInput.select()
            }
        },
        wareChange(){
            this.$nextTick(()=>{
                this.$refs.barCodeInput.focus()
            })
            if(this.form.id){
                this.updateFields()
            }else {
                this.submit()
            }
        },
        async removeCode(){
            if(!this.remove_bar_code) return
            var res = await this.$API.ware.ware.applysend.scan.get({roll_code: this.remove_bar_code,action_type: 2,send_id: this.form.id})
            if(res.code == 1){
                // 创建新的Audio实例播放成功声音，避免连续播放时相互干扰
                const successAudio = new Audio(`${config.API_URL}//audio/ok.wav`);
                successAudio.play();
                const index = this.form.detail.findIndex(item => item.roll_code == this.remove_bar_code)
                if(index !== -1){
                    this.$message.success("删除成功!")
                    this.form.detail.splice(index, 1)
                    this.form.total_num = this.form.detail.length > 0 ? Number(this.form.total_num) - (Number(this.form.detail[index].code_number)).toFixed(2) : 0
                    this.net_weight_total = this.form.detail.length > 0 ? Number(this.net_weight_total) - (Number(this.form.detail[index].net_weight)).toFixed(2) : 0
                    this.form.total_price = this.form.detail.length > 0 ? Number(this.form.total_price) - (Number(this.form.detail[index].process_price)).toFixed(2) : 0
                    // this.form.total_num = Number(this.form.total_num) - (Number(this.form.detail[index].code_number)).toFixed(2)
                    // this.net_weight_total = Number(this.net_weight_total) - (Number(this.form.detail[index].net_weight)).toFixed(2)
                    // 添加条件判断，确保索引赋值的正确性
                    if (this.form.detail && this.form.detail.length > 0) {
                        // 先按原始索引排序，再重新赋值连续索引
                        const sortedItems = [...this.form.detail].sort((a, b) => a.index - b.index);
                        this.form.detail.forEach((item, idx) => {
                            // 查找当前项在排序后的位置，确保索引连续
                            const sortedIndex = sortedItems.findIndex(sortedItem => sortedItem.roll_code === item.roll_code);
                            item.index = sortedIndex !== -1 ? sortedIndex + 1 : idx + 1;
                        });
                        this.table_index = Math.max(...this.form.detail.map(item => item.index));
                    } else {
                        this.table_index = 0;
                    }
                    // this.submit()
                }else {
                    this.$message.error("此条数据不存在!")
                }
                // this.total()
                this.total_count -= 1
            }else {
                // 创建新的Audio实例播放错误声音，避免连续播放时相互干扰
                const errorAudio = new Audio(`${config.API_URL}/audio/error.wav`);
                errorAudio.play();
                this.$message.error(res.message)
                this.$refs.removeBarCodeInput.select()
            }
            this.remove_bar_code = ""
            this.bar_code = ""
        },

        async updateFields(){
            if(!this.form.ware_id) return
            if(this.mode == 'show') return
            let form = {
                id: this.form.id,
                ware_id: this.form.ware_id,
                send_date: this.form.send_date,
                car_code: this.form.car_code,
                car_mobile: this.form.car_mobile,
                remark: this.form.remark,
                total_price: this.form.total_price,
                total_num: this.form.total_num,
            }
            await this.$API.ware.ware.applysend.updateFields.post(form);
            // const successAudio = new Audio(`${config.API_URL}//audio/ok.wav`);
            // successAudio.play();
        },
        music(){
            const successAudio = new Audio(`${config.API_URL}//audio/ok.wav`);
            successAudio.play();
        },
        total(){
            let total_code_number = 0
            let total_money_number = 0
            this.form.detail.map(item=>{
                total_code_number = Number(item.code_number) + total_code_number
                total_money_number = Number(item.process_price) + total_money_number
            })
            this.form.total_num = (total_code_number).toFixed(2)
            this.form.total_price = (total_money_number).toFixed(2)
            this.updateFields()
        }
    }
}
</script>

<style lang="scss">
.top_flex{
    display: flex;
    justify-content: space-between;
}
</style>
